package com.artron.mediaartron.ui.fragment.home;

import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.artron.baselib.base.BaseFragment;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.WorksApi;
import com.artron.mediaartron.ui.adapter.HomePagerAdapter;
import com.artron.mediaartron.ui.callback.MainActivityCallback;
import com.artron.mediaartron.ui.callback.ShowMainMenuItemCallback;
import com.artron.mediaartron.ui.callback.TitleChangeCallback;
import com.artron.mediaartron.ui.callback.ToolbarShowOrGoneCallback;
import com.artron.mediaartron.ui.fragment.factory.HomeFragmentFactory;
import com.artron.mediaartron.ui.fragment.login.LoginWrapperFragment;
import com.artron.mediaartron.ui.helper.BottomNavigationViewHelper;
import com.artron.mediaartron.ui.widget.CustomViewPager;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-20.
 */

public class MainFragment extends BaseStaticFragment implements MainActivityCallback {

    @BindView(R.id.MainFragment_pager)
    protected CustomViewPager mViewPager;
    @BindView(R.id.MainFragment_bnv)
    protected BottomNavigationView mBottomNavigationView;
    private TextView mTvPoint;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initView() {
        BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                mViewPager.setCurrentItem(item.getOrder());
                return true;
            }
        });

        HomePagerAdapter adapter = new HomePagerAdapter(getChildFragmentManager(), 3);
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            private MenuItem menuItem;

            @Override
            public void onPageSelected(int position) {

                if (position == 0) {
                    ((ToolbarShowOrGoneCallback) getActivity()).setToolbarShow(false);
                } else {
                    ((ToolbarShowOrGoneCallback) getActivity()).setToolbarShow(true);
                }
                ((ShowMainMenuItemCallback) getActivity()).showMainMenuItem(position == 1, position == 2);

                if (position == 1) {
                    BaseFragment fragment = HomeFragmentFactory.getInstance().getFragment(position);
                    if (fragment instanceof LoginWrapperFragment) {
                        BaseFragment contentFragment = ((LoginWrapperFragment) fragment).getContentFragment();
                        if (contentFragment instanceof BaseLoadingFragment) {
                            ((BaseLoadingFragment) contentFragment).showImmediate();
                        }
                    }
                }
                String title = HomeFragmentFactory.getInstance().getTitle(position);
                ((TitleChangeCallback) getActivity()).setTitle(title);

                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    mBottomNavigationView.getMenu().getItem(0)
                            .setChecked(false);
                }
                menuItem = mBottomNavigationView.getMenu().getItem(position);
                menuItem.setChecked(true);
            }
        });

        initBluePoint();


        ((ToolbarShowOrGoneCallback) getActivity()).setToolbarShow(false);
    }

    private void initBluePoint() {
        mBottomNavigationView.post(new Runnable() {
            @Override
            public void run() {
                for (int x = 0; x < mBottomNavigationView.getChildCount(); x++) {
                    View targetView = mBottomNavigationView.getChildAt(x);
                    if (targetView instanceof ViewGroup) {
                        ViewGroup childAt = (ViewGroup) targetView;
                        for (int y = 0; y < childAt.getChildCount(); y++) {
                            View child = childAt.getChildAt(y);
                            // TODO
                            if (y == 1) {
                                if (child instanceof BottomNavigationItemView && mTvPoint == null) {
                                    BottomNavigationItemView parent = (BottomNavigationItemView) child;

                                    mTvPoint = UIUtils.inflate(R.layout.layout_main_point, parent);
                                    mTvPoint.setVisibility(View.GONE);
                                    FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)
                                            mTvPoint.getLayoutParams();
                                    for (int z = 0; z < parent.getChildCount(); z++) {
                                        View shoppingCartView = parent.getChildAt(z);
                                        if (shoppingCartView instanceof ImageView) {
                                            ImageView ivImage = (ImageView) shoppingCartView;
                                            int width = ivImage.getWidth();
                                            params.leftMargin = width / 2 - 5;
                                            params.topMargin = 8;
                                        }
                                    }

                                    parent.addView(mTvPoint, params);
                                }
                            }
                        }
                        initShoppingItemNum();
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        if (mViewPager != null) {
            mViewPager.setAdapter(null);
        }
        super.onDestroy();
    }

    @Override
    public void refreshData() {
        int currentItem = mViewPager.getCurrentItem();
        if (currentItem == 2) {
            BaseFragment fragment = HomeFragmentFactory.getInstance()
                    .getFragment(HomeFragmentFactory.MY_CENTER);
            ((MainActivityCallback) fragment).refreshData();
        }
        HomeFragmentFactory instance = HomeFragmentFactory.getInstance();
        BaseFragment fragment1 = instance.getFragment(HomeFragmentFactory.SHOPPING_CART);
        if (fragment1.isAdded()) {
            ((LoginWrapperFragment) fragment1).resetView();
        }
    }

    @Override
    public void initShoppingItemNum() {
        if (mTvPoint == null) {
            return;
        }

        WorksApi api = RetrofitHelper.getWorksApi();
        boolean login = AppProfile.getUserInfo().isLogin();
        if (login) {
            String passId = AppProfile.getUserInfo().getPassId();
            RetrofitHelper.subscript(api.queryTrolleyWorksCount(passId), new Action1<Response<Integer>>() {
                @Override
                public void call(Response<Integer> response) {
                    if ("1".equals(response.getStatus())) {
                        int num = response.getData();
                        if (num == 0) {
                            mTvPoint.setText(0 + "");
                            mTvPoint.setVisibility(View.GONE);
                        } else {
                            mTvPoint.setVisibility(View.VISIBLE);
                            mTvPoint.setText(num + "");
                        }
                    }
                }
            });
        } else {
            mTvPoint.setText(0 + "");
            mTvPoint.setVisibility(View.GONE);
        }


    }

}
